const Redis=require('ioredis');
const redis=new Redis({db:6});
const config=require('../config/config');

module.exports={
    addLimit:opts=>{
         return redis.setex(join(opts.action+'Limit',opts.id),config.accessFrequencyLimit,new Date().toLocaleString());
    },
    getLimit:opts=>{
        return redis.get(join(opts.action+'Limit',opts.id));
    },
    addActivated:async user=>{
        let saveRet=await Promise.all([
            redis.setex(join('activated-name&email',user.name+'&'+user.email),config.activated.expire,user.id),
            redis.hmset(join('activated-id',user.id),user)
        ]);
        let expireRet=await redis.expire(join('activated-id',user.id),config.activated.expire);
        return [...saveRet,expireRet];
    },
    getActivatedByName:name=>{
        return redis.get(join('activated-name&email',name));
    },
    getActivatedById:id=>{
        return redis.hgetall(join('activated-id',id));
    },
    delUser:async user=>{
        return Promise.all([
            redis.del(join('activated-name&email',user.name+'&'+user.email)),
            redis.del(join('activated-id',user.id))
        ]);
    }
};

function join(...ns) {
    ns.unshift(config.name);
    return ns.join(':');
}